import http from "@/api/http.js";
import httpConfig from "@/api/http.js"
const secret = httpConfig.secret
import {
	hex_sha1
} from '@/utils/sha1.js'
/* 对象key 排序*/
const objKeySort = arys => {
	var newkey = Object.keys(arys).sort();
	var newObj = {};
	for (var i = 0; i < newkey.length; i++) {
		newObj[newkey[i]] = arys[newkey[i]];
	}
	return JSON.stringify(newObj)
}
class Tools {
	 
	cloneData(data) {
		return JSON.parse(JSON.stringify(data));
	};
 
	customUpload(filePath, link = "/api/client/index/upload", formData = {
		target: 'oss',
		type: 'media'
	}) {
		return new Promise((resolve, reject) => {
			const url = http.baseUrl + link;
			let sign = hex_sha1(secret + objKeySort(formData))
			uni.showLoading({
				title: '上传中'
			})
			uni.uploadFile({
				url: url,
				filePath,
				name: 'file',
				formData,
				header: {
					sign,
					hostname: httpConfig.hostname
				},
				success: (response) => {
					uni.hideLoading()
					const res = JSON.parse(response.data)
					if (res.code == 1) {
						resolve(res.data);
					} else {
						console.log('res.msg: ', res.msg);
						uni.$u.toast(res.msg);
					}
					uni.hideLoading()
				},
				fail: (err) => {
					uni.hideLoading()
					uni.$u.toast('文件上传失败，请稍后重试');
				}
			});
		})
	}
 
	upload(link = "/api/client/index/upload", formData = {
		target: 'oss',
		type: 'image'
	}, num = 1) {

		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: num,
				success: function(res) {
					res.tempFilePaths.forEach((item, index) => {
						const url = http.baseUrl + link;
						let sign = hex_sha1(secret + objKeySort(formData))
						uni.showLoading({
							title: '上传中'
						})
						uni.uploadFile({
							url: url,
							filePath: item,
							name: 'file',
							formData,
							header: {
								sign,
								hostname: httpConfig.hostname
							},
							success: (response) => {
								uni.hideLoading()
								const res = JSON.parse(response.data)
								if (res.code == 1) {
									resolve(res.data);
								} else {
									uni.$u.toast(res.msg);
								}
							},
							fail: (err) => {
								uni.hideLoading()
								uni.$u.toast('上传失败，请重试');
							}
						});
					})
				},
				fail() {
					reject()
				}
			})
		})
	};
	/* 
	  跳转详情
	*/
	jumpDetail(id) {
		uni.navigateTo({
			url: '/subPages/lineDetail/lineDetail?id=' + id
		})
	}
 
	jumpTo(link, type, scs) {
		type = type || 1;
		scs = scs || function() {};
		// type 1-navigateTo  2-switchTab  3-reLaunch
		if (type == 1) {
			uni.navigateTo({
				url: link,
				success: scs
			});
		} else if (type == 2) {
			uni.switchTab({
				url: link,
				success: scs
			});
		} else if (type == 3) {
			uni.reLaunch({
				url: link,
				success: scs
			});
		} else if (type == 4) {
			uni.redirectTo({
				url: link,
				success: scs
			});
		} else if (type == 5) {
			// 跳转外链
			// #ifdef MP || APP-PLUS 
			plus.runtime.openURL(link);
			// #endif
			// #ifdef H5
			window.location.href = link;
			// #endif
		}
	};
 
	getRect(selector, el, all) {
		return new Promise(resolve => {
			let query = null;
			// 支付宝小程序不能加后面的.in(this)，是它自身的限制
			// #ifndef MP-WEIXIN
			query = uni.createSelectorQuery().in(el);
			// #endif
			// #ifdef MP-ALIPAY
			query = uni.createSelectorQuery()
			// #endif
			query[all ? 'selectAll' : 'select'](selector)
				.boundingClientRect(rect => {
					if (all && Array.isArray(rect) && rect.length) {
						resolve(rect)
					}
					if (!all && rect) {
						resolve(rect)
					}
				})
				.exec()
		})
	};
 
	oss(url, w = 120, h = 120, modenum = 2, type = '', format = 'png', resize = 'resize', multiple = 1) {
		let image = '';
		let mode = ["m_lfit", "m_mfit", "m_fill", "m_fixed"];
		// 图像，自适应方向：1，渐进显示：1，转换格式：png，图片质量：q_90，图片锐化：50，浓缩图
		let rule = ["?x-oss-process=image", "auto-orient,1", "interlace,1", "format,png", "quality,q_90",
			"sharpen,50",
			"resize,m_fixed,w_120,h_120"
		];
		// 转换格式
		if (format == 'png') {
			rule[3] = ["format", "png"].join(",");
		}
		// 判断是否有高度
		if (w == 0) {
			rule[6] = [resize, mode[modenum], `h_${h * multiple}`].join(",");
		} else if (h == 0) {
			rule[6] = [resize, mode[modenum], `w_${w * multiple}`].join(",");
		} else {
			rule[6] = [resize, mode[modenum], `w_${w * multiple}`, `h_${h * multiple}`].join(",");
		}
		//当地址不存在
		if (url) {
			if ((/^data:image\//.test(url))) {
				image = url;
			} else if ((/^(http|https):\/\/.+/.test(url))) {
				// rule.pop();
				image = type == 'video' ? url : (url + rule.join("/"));
			} else {
				// image = type == 'video' ? (config.cdnurl + url) : (config.cdnurl + url + rule.join("/"));
			}
		} else {
			image = url
		}
		return image;
	}
 
	sys = () => {
		const sys = uni.getSystemInfoSync();
		const data = {
			top: sys.statusBarHeight,
			height: sys.statusBarHeight + uni.upx2px(90),
			screenHeight: sys.screenHeight,
			platform: sys.osName,
			model: sys.model,
			windowHeight: sys.windowHeight,
			windowBottom: sys.windowBottom,
			windowTop: sys.windowTop,
			deviceId: sys.deviceId,
			safeAreaInsets: sys.safeAreaInsets
		};
		// // #ifdef MP-WEIXIN || MP-BAIDU || MP-QQ || MP-TOUTIAO || MP-WEIXIN
		// const custom = uni.getMenuButtonBoundingClientRect();
		// data.height = custom.bottom + custom.top - sys.statusBarHeight;
		// // #endif		
		// #ifdef MP-ALIPAY
		data.height = sys.statusBarHeight + sys.titleBarHeight;
		// #endif
		return data;
	};
	/* 返回上一页并调用上页方法 携带参数 
	 @param method：string
	 @param param：any 
	*/
	naviBackEmit = (method, param, delta = 1) => {
		let pages = getCurrentPages()
		// 上一页页面实例
		let prevPage = pages[pages.length - delta - 1];
		// let prevPage = pages[pages.length - 2];
		if (method && prevPage.$vm[method]) prevPage.$vm[method](param)
		uni.navigateBack({
			delta: delta
		});
	};
	/* 
	 * 返回上一页 并修改页面栈data变量
	 * @param data:string
	 * @param param:any
	 */
	naviBackChange = (data, param, delta = 1) => {
	
		
		
		let pages = getCurrentPages()
		let prevPage = pages[pages.length - delta - 1];
		console.log(prevPage.$vm['info.address']);
		console.log(	prevPage.$vm[data],'	prevPage.$vm[data]');
		prevPage.$vm[data] = param
	
		uni.navigateBack({
			delta: delta
		});
	};
	/* 
	 * 校验form字段全部必填
	 * @return Boolear
	 * @param that vm实例
	 * @param custormKeys 自定义校验字段
	 * @example this.$tools.validate(this,['name','mobile']):boolean
	 * @ps vm实例自定义validateTip:{name:'请输入名称'},
	 */
	validate(that, custormKeys) {
		let keys = custormKeys || Object.keys(that.form)
		return keys.every(key => {
			if (!that.form[key]) uni.$u.toast(that.validateTip[key])
			return that.form[key]
		})
	}

	/* 
	  复制文本
	*/
	copy = (str) => {
		uni.setClipboardData({
			data: String(str),
			success(res) {
				if (res) {
					uni.showToast({
						icon: 'none',
						title: '复制成功！'
					})
				}
			}
		});
	};
	/* 拨打电话 */
	phone = (phone) => {
		uni.makePhoneCall({
			phoneNumber: phone
		});
	}
 
	static instance;
	static getInstance() {
		// console.log(Request.instance)
		if (!Tools.instance) {
			Tools.instance = new Tools();
		}

		return Tools.instance;
	}

}

export default Tools.getInstance();